package com.stack.auto_parts.controller;

import com.stack.auto_parts.common.ApiResult;
import com.stack.auto_parts.common.JWT.JwtUtil;
import com.stack.auto_parts.entity.LoginResult;
import com.stack.auto_parts.entity.User;
import com.stack.auto_parts.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * @Title: LoginController
 * @Author WUYU_MIN
 * @Package com.stack.auto_parts.controller
 * @Date 2024/7/10 14:33
 * @description:
 */
@Slf4j
@RestController
@CrossOrigin
public class LoginController {

    @Autowired
    private UserService userService;

    /**
     * private String userName;
     *     private String phone;
     *     private String email;
     *     private String password;
     *     private String role;
     *     private String image;
     * @param user
     * @return
     */
    @PostMapping("/login")
    public ApiResult<LoginResult> login(@RequestBody User user){
        log.info("登录！" + user.getPhone() + user.getPassword());

        User users = userService.login(user.getPhone() , user.getPassword());
        if(users != null){
            Map<String,Object> claim = new HashMap<>();
            claim.put("uuid",users.getUuid());
            claim.put("name",users.getUserName());
            //claim.put("password",users.getPassword());

            String jwt = JwtUtil.generateJwt(claim);
            LoginResult container = new LoginResult(jwt,users.getId(),users.getUuid(), users.getUserName(),users.getPhone(),users.getEmail(),users.getRole(),users.getImage());

            return ApiResult.success(container);

        }
        return ApiResult.fail("用户名或密码错误");
    }


}
